package com.kll.carolinehmibiz.model

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kll.carolinehmibiz.base.utils.L
import com.kll.carolinehmibiz.base.utils.SpUtils
import com.kll.carolinehmibiz.net.bean.LoginResponse


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/8 20:16
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class AccountModel {

    private var loginInfos: ArrayList<LoginResponse> = arrayListOf()
//    private var tokens: ArrayList<LoginResponse.UserToken> = arrayListOf()
    private var mSn: String? = null
    private var mUserSig: String? = null
    private var mSdkappid: String? = null
    private var mIsActive: Int = -1

    private var mContext: Context? = null
    private var mCurrentIndex = 0

    companion object {

        private var mInstance: AccountModel? = null
        var SN:String?=null
        var mRoomId: Int = 0
        fun getInstance(context: Context): AccountModel{
            if(mInstance == null) {
                mInstance = AccountModel(context)
            }
            return mInstance!!
        }
    }

    constructor(context: Context) {
        mContext = context.applicationContext

        var loginInfoCache = SpUtils.getInstance().getValueByString(context, "LOGIN_INFO")

        if(loginInfoCache != null) {
            loginInfos = Gson().fromJson(loginInfoCache,
                object :TypeToken<ArrayList<LoginResponse>>(){}.type)
        }

        mCurrentIndex = SpUtils.getInstance().getValueByInt(context, "LOGIN_CURRENT_INDEX")
    }

    fun getDeviceActiveStatus(): Int {

        if(mIsActive == -1) {
            mIsActive = (SpUtils.getInstance().getValueByInt(mContext, "DEVICE_ACTIVE_STATUS"))
        }

        return mIsActive
    }

    fun saveDeviceActiveStatus(status: Int) {
        mIsActive = status
        SpUtils.getInstance().saveValueToSharePerference(mContext, "DEVICE_ACTIVE_STATUS", mIsActive)
    }

    fun saveUserSig(userSig: String, sdkAppId:  String) {
        mUserSig = userSig
        mSdkappid = sdkAppId
        SpUtils.getInstance().saveValueToSharePerference(mContext,  "USER_SIG",  mUserSig)
        SpUtils.getInstance().saveValueToSharePerference(mContext,  "SDK_APP_ID",  mSdkappid)
    }

    /**
     * get sdkAppId
     */
    fun getSdkAppId(): String? {
        if(mSdkappid == null) {
            mSdkappid = SpUtils.getInstance().getValueByString(mContext,  "SDK_APP_ID")
        }
        return mSdkappid
    }

    /**
     *
     */
    fun getUserSig(): String? {
        if(mUserSig == null) {
            mUserSig = SpUtils.getInstance().getValueByString(mContext,  "USER_SIG")
        }
        return mUserSig
    }

    fun saveLoginInfo(loginInfo: LoginResponse?){

        if(loginInfo?.user == null || loginInfo.token == null) return

        var index = findAccountByIndex(loginInfo.user!!.mobile)
        if(index != -1) {
            loginInfos[index] = loginInfo
            mCurrentIndex = index
        } else {
            loginInfos.add(loginInfo)
            mCurrentIndex = loginInfos.size - 1
        }

        saveLoginInfoToCache()
        saveLoginCurrentIndexToCache()
    }

    /**
     * 更改用户token
     */
    fun updateUserToken(token: String) {
        if (mCurrentIndex >= 0 && loginInfos.size > mCurrentIndex) {
            loginInfos[mCurrentIndex].token!!.token = token

            saveLoginInfoToCache()
        }
    }

    private fun saveLoginInfoToCache(){
        SpUtils.getInstance().saveValueToSharePerference(mContext, "LOGIN_INFO", Gson().toJson(loginInfos))
    }

    private fun saveLoginCurrentIndexToCache(){
        SpUtils.getInstance().saveValueToSharePerference(mContext, "LOGIN_CURRENT_INDEX", mCurrentIndex)
    }

    /**
     * 查找用户所在的下标
     */
    private fun findAccountByIndex(mobile: String): Int {
        for(index in loginInfos.indices) {
            if(loginInfos[index].user!!.mobile == mobile) {
                return index
            }
        }

        return -1
    }

    /**
     * 切换用户
     */
    fun switchAccount(mobile: String) {

        var index = findAccountByIndex(mobile)

        if(index >= 0) {
            mCurrentIndex = index
        }

        saveLoginInfoToCache()
        saveLoginCurrentIndexToCache()
    }

    /**
     * 获取所有用户列表
     */
    fun getAllAccounts(): ArrayList<LoginResponse> {
        return loginInfos
    }

    /**
     * 删除用户
     */
    fun removeAccount(mobile: String) {

        var index = findAccountByIndex(mobile)

        if(index >= 0) {

            loginInfos.removeAt(index)

            if(mCurrentIndex == 0) {
                mCurrentIndex = -1
            }
        }

        saveLoginInfoToCache()
        saveLoginCurrentIndexToCache()
    }

    fun getUserInfo(): LoginResponse.UserInfo? {
        return if(mCurrentIndex >= 0 && loginInfos.size > mCurrentIndex) loginInfos[mCurrentIndex].user!! else null
    }

    fun getUserToken(): LoginResponse.UserToken? {
        return if(mCurrentIndex >= 0 && loginInfos.size > mCurrentIndex) loginInfos[mCurrentIndex].token!! else null
    }

    @SuppressLint("MissingPermission")
    fun getSn(): String? {
        mSn=SpUtils.getInstance().getValueByString(mContext,"SN");
        if(mSn == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                try{
                    mSn = Build.getSerial()
                }catch (e: Exception) {
                    e.printStackTrace()
                    mSn = "${(Math.random() * 100000).toLong()}"
                }

            } else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
                mSn = Build.SERIAL
            }
        }

        if(mSn == null) {
            L.e("AccountModel", ">>>SN码为空，请处理！！！")
        } else {
            L.d("AccountModel","getSn:: mSn = ${mSn}")
        }
        SpUtils.getInstance().saveValueToSharePerference(mContext, "SN",mSn);
        return mSn
    }

    fun clear(){
        if(loginInfos.size > mCurrentIndex) {
            loginInfos.removeAt(mCurrentIndex)
            mCurrentIndex = -1
            saveLoginInfoToCache()
            saveLoginCurrentIndexToCache()
        }
    }


}